package com.benyanyi.floatinginputbox;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;

import com.benyanyi.floatinginputbox.callback.DefaultEditorCallback;
import com.benyanyi.floatinginputbox.callback.EditorCallback;

/**
 * @author YanYi
 * @date 2020/05/23 10:44
 * @email ben@yanyi.red
 * @overview
 */
public class FloatingInputBoxActivity extends Activity implements View.OnClickListener {

    private static final String KEY_EDITOR_HOLDER = "input_box_holder";
    private static final String IS_DEFAULT = "is_default";
    private static final String LEFT_TEXT = "left_text";
    private static final String TITLE = "title";
    private static final String RIGHT_TEXT = "right_text";
    private static final String HINT = "hint";
    private static final String MSG = "msg";

    private static EditorCallback mEditorCallback;
    private static DefaultEditorCallback mDefaultEditorCallback;

    private EditorHolder holder;

    private boolean isDefault = false;

    private TextView cancel;
    private TextView title;
    private TextView submit;
    private EditText etContent;

    private boolean isClicked;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isDefault = getIntent().getBooleanExtra(IS_DEFAULT, false);
        holder = (EditorHolder) getIntent().getSerializableExtra(KEY_EDITOR_HOLDER);
        if (holder == null && !isDefault) {
            throw new RuntimeException("EditorHolder params not found!");
        }
        if (isDefault) {
            setContentView(R.layout.default_input_box);
        } else {
            setContentView(holder.layoutResId);
        }
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        getWindow().setGravity(Gravity.BOTTOM);
        if (isDefault) {
            initView();
            setEvent();
        } else {
            if (mEditorCallback != null) {
                EditText editText = mEditorCallback.callback(this);
                if (editText != null) {
                    showSoftInputFromWindow(editText);
                }
            }
        }
    }

    private void initView() {
        cancel = findViewById(R.id.tv_cancel);
        cancel.setText(getIntent().getStringExtra(LEFT_TEXT));
        title = findViewById(R.id.tv_title);
        title.setText(getIntent().getStringExtra(TITLE));
        submit = findViewById(R.id.tv_send);
        submit.setText(getIntent().getStringExtra(RIGHT_TEXT));
        etContent = findViewById(R.id.et_write);
        etContent.setHint(getIntent().getStringExtra(HINT));
        showSoftInputFromWindow(etContent);
    }

    private void setEvent() {
        if (cancel != null)
            cancel.setOnClickListener(this);

        submit.setOnClickListener(this);
    }

    public static void openInputBox(Context context, @LayoutRes int layoutID, EditorCallback editorCallback) {
        Intent intent = new Intent(context, FloatingInputBoxActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(IS_DEFAULT, false);
        intent.putExtra(KEY_EDITOR_HOLDER, new EditorHolder(layoutID));
        mEditorCallback = editorCallback;
        context.startActivity(intent);
    }

    public static void openDefaultInputBox(Context context, DefaultEditorCallback defaultEditorCallback) {
        openDefaultInputBox(context, new DefaultUiConfig(), "", defaultEditorCallback);
    }

    public static void openDefaultInputBox(Context context, String editMsg, DefaultEditorCallback defaultEditorCallback) {
        openDefaultInputBox(context, new DefaultUiConfig(), editMsg, defaultEditorCallback);
    }

    public static void openDefaultInputBox(Context context, DefaultUiConfig defaultUiConfig, DefaultEditorCallback defaultEditorCallback) {
        openDefaultInputBox(context, defaultUiConfig, "", defaultEditorCallback);
    }

    public static void openDefaultInputBox(Context context, DefaultUiConfig defaultUiConfig, String editMsg, DefaultEditorCallback defaultEditorCallback) {
        Intent intent = new Intent(context, FloatingInputBoxActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(IS_DEFAULT, true);
        DefaultUiConfig uiConfig = defaultUiConfig;
        if (uiConfig == null) {
            uiConfig = new DefaultUiConfig();
        }
        intent.putExtra(LEFT_TEXT, uiConfig.getLeftText());
        intent.putExtra(TITLE, uiConfig.getTitle());
        intent.putExtra(RIGHT_TEXT, uiConfig.getRightText());
        intent.putExtra(HINT, uiConfig.getHint());
        intent.putExtra(MSG, editMsg);
        mDefaultEditorCallback = defaultEditorCallback;
        context.startActivity(intent);
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    private void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (mDefaultEditorCallback != null) {
            if (id == R.id.tv_cancel) {
                mDefaultEditorCallback.onCancel();
            } else if (id == R.id.tv_send) {
                mDefaultEditorCallback.onSubmit(etContent.getText().toString());
            }
        }
        hintKbTwo();
        isClicked = true;
        finish();
    }

    /**
     * 关闭软键盘
     */
    private void hintKbTwo() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && inputMethodManager.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isDefault && !isClicked && mDefaultEditorCallback != null) {
            mDefaultEditorCallback.onCancel();
        }
        mEditorCallback = null;
    }
}
